/*
 * DogeMainWindow.java
 *
 * Created on 15 luglio 2007, 13.01
 */

package dogeUI;

import dogeCore.*;
import dogeDB.*;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

/**
 *
 * @author  daniele
 */
public class DogeMainWindow extends javax.swing.JFrame {
    
    /**
     * Creates new form DogeMainWindow
     */
    public DogeMainWindow(DogeCore core) {
        this.core=core;
        initComponents();
        //create login panel
        newLogin();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        footerLabel = new javax.swing.JLabel();
        headerLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("DoGe - Bell'Arte Tessile");
        setMinimumSize(new java.awt.Dimension(900, 600));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        footerLabel.setFont(new java.awt.Font("Dialog", 1, 14));
        footerLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        footerLabel.setText("DoGe - \u00a9 2007 Diesel Team");
        footerLabel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        footerLabel.setEnabled(false);
        getContentPane().add(footerLabel, java.awt.BorderLayout.SOUTH);
        footerLabel.getAccessibleContext().setAccessibleName("aboutLabel");

        headerLabel.setFont(new java.awt.Font("Dialog", 1, 36));
        headerLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dogeUI/images/logodoge.jpg")));
        headerLabel.setText("DoGe - Bell'Arte Tessile");
        headerLabel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        headerLabel.setMinimumSize(new java.awt.Dimension(300, 96));
        headerLabel.setPreferredSize(new java.awt.Dimension(600, 96));
        getContentPane().add(headerLabel, java.awt.BorderLayout.NORTH);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        terminateDoge();
    }//GEN-LAST:event_formWindowClosing
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                String host=getHostFromConfig();
                new DogeMainWindow(new DogeCore(new DogeMysql(host))).setVisible(true);
            }
        });
    }

    /** reads config file dogeConfig/DogeConfig.xml to get database machine hostname */
    private static String getHostFromConfig(){
        try {
            //variables to parse xml document
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            //open xml config file
            Document doc = docBuilder.parse(new File("DogeConfig.xml"));
            //get <host> nodes (there's only one...)'
            NodeList hostList = doc.getElementsByTagName("host");
            Element hostElement = (Element)hostList.item(0);
            NodeList textHostList = hostElement.getChildNodes();
            Node hostNode = (Node)textHostList.item(0);
            //return <host></host> value
            return hostNode.getNodeValue().trim();
        } catch (Exception ex) {
            //in case of exception fall back to default "localhost"
            javax.swing.JOptionPane.showMessageDialog(null,"Si è verificato un errore leggendo il file di configurazione, pertanto il programma verrà avviato con le impostazioni predefinite.\nContattare l'amministratore di sistema per il ripristino del file di configurazione.\n\nIl dettaglio dell'errore è:\n"+ex.getLocalizedMessage(),"Errore nell'accesso al file di configurazione",javax.swing.JOptionPane.ERROR_MESSAGE);
            return "localhost";
        }
    }
    
    /**
     * Redesigns interface after a successful login
     */
    protected void loginSuccessful() {
        //remove login panel...
        remove(loginPanel);
        //... and substitute it with the sidebar menu...
        menuPanel=new DogeMenuFrame(core, this);
        getContentPane().add(menuPanel, java.awt.BorderLayout.WEST);
        //... and a welcome screen
        centerPanel=new DogeWelcomeFrame();
        getContentPane().add(centerPanel, java.awt.BorderLayout.CENTER);
        validate();
}

    /**
     * Terminates DoGe gracefully
     */
    void terminateDoge() {
        try {
            //ask core to terminate
            core.terminateDoge();
            //exit with no error state
            System.exit(0);
        } catch (SQLException ex) {
            System.exit(1);
        }
    }

    /** show (again) the login panel */
    void newLogin() {
        //if they exist remove sidebar and center panel
        if (menuPanel!=null){
            remove(menuPanel);
            menuPanel=null;
        }
        if (centerPanel!=null){
            remove(centerPanel);
            centerPanel=null;
        }
        //create new login panel...
        loginPanel=new DogeLoginFrame(core,this);
        //...insert it...
        getContentPane().add(loginPanel, java.awt.BorderLayout.CENTER);
        //...set default button...
        getRootPane().setDefaultButton(loginPanel.getDefaultButton());
        //...and refresh ui
        validate();
    }

    /** show the insert panel */
    void showInsertPanel() {
        //(if it exists) remove center panel...
        if (centerPanel!=null){
            remove(centerPanel);
            centerPanel=null;
        }
        //...and substitute it with a new insert frame
        centerPanel=new DogeInsertFrame(core);
        getContentPane().add(centerPanel, java.awt.BorderLayout.CENTER);
        //set default button
        getRootPane().setDefaultButton( ((DogeInsertFrame)centerPanel).getDefaultButton() );
        //refresh ui
        validate();
    }

    /** shows the edit panel (not implemented - shows a blank JPanel)*/
    void showEditPanel() {
        //(if it exists) remove center panel...
        if (centerPanel!=null){
            remove(centerPanel);
            centerPanel=null;
        }
        //...and substitute it with a new edit frame
        centerPanel=new javax.swing.JPanel();
        getContentPane().add(centerPanel, java.awt.BorderLayout.CENTER);
        //refresh ui
        validate();
    }

    /** shows the search panel (not implemented - shows a blank JPanel)*/
    void showSearchPanel() {
        //(if it exists) remove center panel...
        if (centerPanel!=null){
            remove(centerPanel);
            centerPanel=null;
        }
        //...and substitute it with a new search frame
        centerPanel=new javax.swing.JPanel();
        getContentPane().add(centerPanel, java.awt.BorderLayout.CENTER);
        //refresh ui
        validate();
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel footerLabel;
    private javax.swing.JLabel headerLabel;
    // End of variables declaration//GEN-END:variables
    //login panel
    private DogeLoginFrame loginPanel;
    //menu panel
    private DogeMenuFrame menuPanel;
    //the panel in the central area of the window
    private javax.swing.JPanel centerPanel;
    //core of DoGe
    private DogeCore core;
}
